<template>
  <div class="custom-table-list-wrapper">
    <div class="search" :class="{ active: toggleSearchStatus }">
      <div class="search-left" ref="searchFromRef">
        <el-form class="search-form" inline>
          <el-form-item label="检查项目类型">
            <el-select
              class="search-select"
              v-model="searchParams.itemTypeIds"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) of dict['inspection_check_project_type']"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检查类型">
            <el-select
              class="search-select"
              v-model="searchParams.typeId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) of dict['inspection_inspection_type']"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="检查场景">
            <el-select
              class="search-select"
              v-model="searchParams.senceId"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="(item, index) of dict['inspection_inspection_scene']"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              class="search-input"
              v-model="searchParams.keyword"
              placeholder="请输入检查内容、检查项编号"
              :suffix-icon="Search"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="search-right">
        <el-button type="primary" @click="initTableList(1)"
          ><svg-icon name="search" size="14px" />搜索</el-button
        >
        <el-button @click="handleReset()"
          ><svg-icon name="reset" size="17px" />重置</el-button
        >
      </div>
    </div>
    <div class="content">
      <div class="content-operate">
        <el-button type="primary" @click="handleClickAdd">
          <svg-icon name="add" size="15px" />新增</el-button
        >
        <!-- <el-upload
          class="custom-upload"
          ref="uploadRef"
          :show-file-list="false"
          action="#"
          :http-request="handleImport"
          accept=".xls,.xlsx"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            <span>批量导入</span>
          </el-button>
        </el-upload>
        <el-button type="primary" @click="handleExport">
          <el-icon>
            <Download />
          </el-icon>
          <span>模版下载</span>
        </el-button> -->
      </div>
      <div class="content-table">
        <el-table class="custom-table" :data="tableData">
          <el-table-column type="index" label="序号" width="60px" />
          <el-table-column prop="code" label="检查项编号" />
          <el-table-column prop="itemTypeName" label="检查项目类型" />
          <el-table-column prop="typeName" label="检查类型">
            <template #default="scope">
              {{
                getDictValue(
                  'inspection_inspection_type',
                  scope.row.typeIds.join(','),
                  true,
                )
              }}
            </template>
          </el-table-column>
          <el-table-column prop="senceName" label="检查场景" />
          <el-table-column prop="content" label="检查内容" />
          <el-table-column prop="createUserName" label="创建人" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="relatedTables" label="关联检查表数" />
          <el-table-column prop="enabled" label="是否启用" width="100">
            <template #default="scope">
              <el-switch
                :active-value="'1'"
                :inactive-value="'0'"
                v-model="scope.row.enabled"
                :before-change="handleChangeStatus.bind(this, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160px">
            <template #default="scope">
              <el-button link type="primary" @click="handleClickEdit(scope.row)"
                >编辑</el-button
              >
              <!-- 关联检查表数=0，可删除 -->
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row)"
                v-if="scope.row.relatedTables === 0"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="content-page">
        <el-pagination
          class="custom-pagination"
          :current-page="paginationParams.pageIndex"
          :page-size="paginationParams.pageSize"
          background
          :page-sizes="[10, 20, 30, 50]"
          layout="total, prev, pager, next, sizes, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="initTableList"
        />
      </div>
    </div>

    <!-- 新增检查项 -->
    <v-modal
      width="500px"
      class="custom-modal"
      :title="addRef.title"
      v-model:visible="addRef.dialogVisible"
      @ok="handleFormOk"
    >
      <el-form
        ref="formRef"
        class="form"
        :model="currentDetail"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="检查项目类型" prop="itemTypeId">
          <el-select
            v-model="currentDetail.itemTypeId"
            placeholder="请选择"
            :disabled="isDisabledBaseInfo"
          >
            <el-option
              v-for="(item, index) of dict['inspection_check_project_type']"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检查类型" prop="typeIds">
          <el-select
            v-model="currentDetail.typeIds"
            placeholder="请选择"
            multiple
            :disabled="isDisabledBaseInfo"
          >
            <el-option
              v-for="(item, index) of dict['inspection_inspection_type']"
              :key="index"
              :label="item.name"
              :value="item.value"
              :disabled="item.value === '4'"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检查场景" prop="senceIds">
          <el-select
            v-model="currentDetail.senceIds"
            multiple
            placeholder="请选择"
            :disabled="isDisabledBaseInfo"
          >
            <el-option
              v-for="(item, index) of dict['inspection_inspection_scene']"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检查内容" prop="content">
          <el-input
            v-model="currentDetail.content"
            :rows="2"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="出处法规、条例" prop="regulations">
          <el-input
            v-model="currentDetail.regulations"
            :rows="2"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="currentDetail.remark"
            :rows="2"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="currentDetail.enabled">
            <el-radio
              v-for="(item, index) of dict['yn']"
              :key="index"
              :value="item.value"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
    </v-modal>
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { useTableList } from '@/hooks/useTableList'
import vModal from '@/components/modal/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  addCheckProject,
  getCheckProjectList,
  getCheckProjectDetail,
  updateCheckProject,
  deleteCheckProject,
  importCheckProject,
  exportCheckProject,
} from '@/api/manager/inspectionManage/checkItemManage.js'

import { Download, Upload } from '@element-plus/icons-vue'

import { useDict } from '@/hooks/useDict'

const { dict, getDictValue } = useDict([
  'inspection_check_project_type',
  'inspection_inspection_type',
  'inspection_inspection_scene',
  'yn',
])

const searchParams = ref({})

const {
  Search,
  toggleSearchStatus,
  tableData,
  paginationParams,
  total,
  addRef,
  currentDetail,
  initTableList,
  handleSizeChange,
  handleReset,
  handleDelete,
  handleAdd,
  handleEdit,
  searchFromRef,
} = useTableList(searchParams, getCheckProjectList, deleteCheckProject)

const formRef = ref()

// 表单数据
currentDetail.value = {
  inspectItemType: '',
  typeIds: [],
  senceIds: [],
  content: '',
  regulations: '',
  remark: '',
  enabled: '1',
}

const rules = {
  itemTypeId: [
    { required: true, message: '请选择检查项目类型', trigger: 'change' },
  ],
  typeIds: [{ required: true, message: '请选择检查类型', trigger: 'change' }],
  senceIds: [{ required: true, message: '请选择检查场景', trigger: 'change' }],
  content: [{ required: true, message: '请输入检查内容', trigger: 'blur' }],
}

// 关联检查表数>0,
// 仅可编辑检查内容、出处法规、条例、备注、状态
const isDisabledBaseInfo = ref(false)
const handleClickAdd = () => {
  handleAdd('新增检查项')
  currentDetail.value = { enabled: '1' }
  isDisabledBaseInfo.value = false
}
const handleClickEdit = async ({ pkid, relatedTables }) => {
  if (relatedTables === 0) {
    isDisabledBaseInfo.value = false
  } else {
    isDisabledBaseInfo.value = true
  }
  const res = await getCheckProjectDetail({ pkid })
  if (res.success) {
    handleEdit(res.data, '编辑检查项')
  }
}

const handleAddFn = async () => {
  await addCheckProject({
    ...currentDetail.value,
  })
  ElMessage.success('新增成功')
  addRef.value.dialogVisible = false
  initTableList()
}

const handleEditFn = async () => {
  await updateCheckProject(currentDetail.value)
  ElMessage.success('编辑成功')
  addRef.value.dialogVisible = false
  initTableList()
}

const handleFormOk = async () => {
  if (!formRef.value) return
  formRef.value.validate(async (valid) => {
    if (valid) {
      addRef.value.type === 'add' ? handleAddFn() : handleEditFn()
    }
  })
}

const handleChangeStatus = async (row) => {
  return new Promise((resolve) => {
    ElMessageBox.confirm(`是否切换启用状态`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const res = await updateCheckProject({
          ...row,
          enabled: row.enabled === '1' ? '0' : '1',
        })
        if (res.success) {
          ElMessage.success('切换成功')
          resolve(true)
        } else {
          ElMessage.error(res.message)
          resolve(false)
        }
      })
      .catch(() => {
        resolve(false)
      })
  })
}

// 导入
const handleImport = async (param) => {
  const formData = new FormData()
  formData.append('file', param.file)
  const res = await importCheckProject(formData)
  if (res.success) {
    ElMessage.success(res.message)
    initTableList(1)
  } else {
    ElMessage.error(res.message)
  }
}
// 导出
const handleExport = async () => {
  const res = await exportCheckProject()
  let blobUrl = window.URL.createObjectURL(
    new Blob([res], {
      type: 'application/excel',
    }),
  )
  let fileName = `检查项导入模版.xlsx`
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = blobUrl
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
onMounted(() => {
  initTableList()
})
</script>
<style lang="scss" scoped>
@import '@/assets/styles/table.scss';

.content {
  .content-operate {
    display: flex;
    justify-content: flex-start;
  }

  // .custom-content-table {
  //   flex: 1;
  //   overflow: hidden;
  // }
}

.form {
  position: relative;
  padding: 20px;
}

.custom-upload {
  margin: 0 10px;
}
</style>
